package com.zhanglijie.improve.atomic.four;

import java.lang.reflect.Field;

import fr.ujm.tse.lt2c.satin.cache.size.CacheInfo;
import sun.misc.Unsafe;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/8 0008 23:49
 */
public class MySafeRefence<V> {

    final Unsafe unsafe = getUnsafe();
    private final long offset;
    private final Class<V> classz;

    public MySafeRefence(String  fieldName, Class<V> classz) {
        Field field = null;
        try{
            field = classz.getDeclaredField(fieldName);
        }catch (Exception e){}

        this.offset = unsafe.objectFieldOffset(field);
        this.classz = classz;
    }

    public static Unsafe getUnsafe(){

        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            Unsafe obj = (Unsafe) theUnsafe.get(null);//静态变量给个null 实例变量给当前实例对象
            return obj ;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public int addAndGet(V obj,int num){
        return getAndAdd(obj,num)+num;
    }

    public int getAndAdd(V obj, int num) {
        return unsafe.getAndAddInt(obj,offset,num);
    }


}
